package com.xiang.api.config;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.ValueFilter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;

import com.xiang.api.Util;
import com.xiang.api.config.MyConfig.MyConfig;

import jakarta.annotation.Nonnull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
  @Autowired
  MyConfig myConfig;

  @Override
  public void configureMessageConverters(@SuppressWarnings("null") List<HttpMessageConverter<?>> converters) {
    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); // @ResponseBody 解决乱码
    converters.add(new ResourceHttpMessageConverter());
    converters.add(new AllEncompassingFormHttpMessageConverter());
    converters.add(fastJsonHttpMessageConverter());
    Util.test();
    System.out.println("\nhttp://localhost:" + myConfig.login.port + "\n");
    // codeGenerator.generator(true);
  }

  private FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    config.setCharset(StandardCharsets.UTF_8);
    config.setWriterFeatures(JSONWriter.Feature.WriteLongAsString, JSONWriter.Feature.WriteBigDecimalAsPlain,
        JSONWriter.Feature.WriteByteArrayAsBase64, JSONWriter.Feature.WriteNullNumberAsZero,
        JSONWriter.Feature.WriteNullStringAsEmpty, JSONWriter.Feature.WriteNullBooleanAsFalse,
        JSONWriter.Feature.WriteNullListAsEmpty);
    config.setWriterFilters(valueFilter);

    converter.setFastJsonConfig(config);
    // 解决中文乱码问题，相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
    converter.setDefaultCharset(StandardCharsets.UTF_8);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.APPLICATION_JSON);
    converter.setSupportedMediaTypes(mediaTypeList);
    return converter;
  }

  /**
   * FastJson过滤器将null值转换为字符串 obj 是class s 是key值 o1 是value值
   */
  public static final ValueFilter valueFilter = (obj, s, v) -> {
    if (v == null) {
      return "";
    }
    return v;
  };

  // 跨域配置
  @Override
  public void addCorsMappings(@SuppressWarnings("null") @Nonnull CorsRegistry registry) {
    if (registry == null) {
      return;
    }
    // 添加映射路径
    registry.addMapping("/**")
        .allowCredentials(true) // 是否发送Cookie
        .allowedOriginPatterns("*")
        // .allowedOrigins("*") // 设置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins("*")
        .allowedMethods("GET", "POST", "OPTIONS") // 放行哪些请求方式 // .allowedMethods("*") // 或者放行全部
        .allowedHeaders("*") // 放行哪些原始请求头部信息
        .exposedHeaders("token") // 暴露哪些原始请求头部信息
        .maxAge(3600); // 可选，设置预检请求的有效期，减少重复的预检请求
  }
}
